var express = require('express');
var router = express.Router();
//载入加密的第三方模块 bcryptjs
const bcrypt = require('bcryptjs')

//导入前台的用户模型
const UserModel = require('../../models')['User']

//导入用于生成JWT字符串的包
const jwt = require('jsonwebtoken')

//注册
//使用joi去做表单项验证（省略）
router.post('/reg', async (req, res) => {
    try {
        //接收用户名和密码
        let username = req.body.username.trim();
        let password = req.body.password.trim();
        //密码加密
        password = bcrypt.hashSync(password, 10);

        //唯一性验证
        const users = await UserModel.findAll({
            where: {
                username
            }
        })
        if (users.length > 0) {
            return res.cc(400, '该用户已经注册过')
        }
        const result = await UserModel.create({
            username,
            password,
            createdAt: new Date(),
            updatedAt: new Date()
        });
        res.cc(201, '注册成功', result);
    } catch (e) {
        res.cc(400, e.message);
    }
})

//登录
router.post('/login', async (req, res) => {
    try {
        //接收用户名和密码
        let username = req.body.username.trim();
        let password = req.body.password.trim();
        //验证用户名是否正确
        let userinfo=await UserModel.findOne({
            where:{
               username
            }  
        })
        if(!userinfo){
            return res.cc(400,'用户名或者密码不正确')
        }

        //对用户输入的密码和查询出来的数据的密码进行比对
        const compareResult = bcrypt.compareSync(password,userinfo.password)
        if (!compareResult){
            return res.cc(400, '用户名或者密码不正确')
        }
        //保存用户的id到jwt中
        let token = jwt.sign({
            user_id: userinfo.id,
            user_name:userinfo.username
        }, 'kuaijian', {
            expiresIn: 3600 * 10
        })
        res.cc(200, '查询成功', 'Bearer ' + token);

    } catch (e) {
        res.cc(400, e.message);
    }

})

module.exports = router